package org.jlamp.server.handler;

import com.alibaba.fastjson.JSON;
import org.jlamp.server.JlampPoint;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.*;

/**
 * @author zhangcs
 */
public class ThreadsPoint implements JlampPoint {

    @Override
    public String url() {
        return "threads";
    }

    @Override
    public String read() {
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        long[] threadIds = bean.getAllThreadIds();
        ThreadInfo[] threadInfos = bean.getThreadInfo(threadIds);

        List<Map<String, Object>> result = new ArrayList<>(16);
        Arrays.stream(threadInfos).forEach(threadInfo -> {
            Map<String, Object> map = new HashMap<>(16);
            map.put("id", threadInfo.getThreadId());
            map.put("name", threadInfo.getThreadName());
            map.put("state", threadInfo.getThreadState());
            result.add(map);
        });

        return JSON.toJSONString(result);
    }

    @Override
    public String describe() {
        return "Get all threads";
    }

}
